<?php
namespace   Home\Model;

use Think\Model;

class ApiModel extends Model {

    protected $tableName = 'choujiang_gift';

    function _initialize() {
        $this->ApiModel = M("choujiang_gift");
    }

    public function  gjjk($round,$user){
        // 如果当前用户不是消费者,不能参与抽奖
        if($user['type'] !=1 ) {
            throw new \Exception("您不能参与抽奖哦,请联系管理员", 1701);  
        }
        //如果不是注册轮抽奖(round=1)而且当前用户在7日内抽过奖,也不能参与抽奖
        if($round!=1){
            $last_cj_history=M('choujiang_history')->field('created_at')->where('round !=1 and user_id='.$user['id'])->order('id desc')->find();
            if($last_cj_history && $last_cj_history['created_at']>time()-7*24*3600){
                $seconds = $last_cj_history['created_at']+7*24*3600-time();
                throw new \Exception("您7天内已参与过抽奖哦,请".convert_seconds($seconds).'后再来^_^', 1702); 
            }
        }
        $cur_gailv = rand(1,100);
        //取得当前轮次的全局概率,如果没有进入全局概率范围,则直接返回不中奖
        $global_cur_round_gailv = M('choujiang_round')->field('gailv')->where('round='.$round)->find();

        if(!$global_cur_round_gailv){
            //没中奖,这里复位中奖数据给$got_gift
            $got_gift = $this->noGift($cur_gailv,-1);
            return $got_gift;
        }
        if($cur_gailv>$global_cur_round_gailv['gailv']){
            //没有进入全局概率范围,不能中奖,这里复位中奖数据给$got_gift
            $got_gift = $this->noGift($cur_gailv,$global_cur_round_gailv['gailv']);
            return $got_gift;
        }
        //下面开始选取已启用的并且已中出数小于可中出数的指定轮次奖品,并根据概率进行抽奖
        $guangDongSpecialid=C('GUANG_DONG_REGISTER_GIFT_ID');
        $map['round']=$round;
        $map['count'] = array('exp', '> used_count');
        $map['status']=1;
        $map['id'] = array('exp', '!='.$guangDongSpecialid);
        //如果是注册轮抽奖而且抽奖用户来自广东,则只能中出指定礼品
        if($round==1){
            if($user['r_province'] == '广东'){
                $map['id'] = $guangDongSpecialid;
                // $got_gift = $this->ApiModel->where($gmap)->find();
                // $got_gift['random_val']=-2;
                // return $got_gift;
            }
        }
        
        $cc=$this->ApiModel->where($map)->select();
        // shuffle($cc);
        $ljgaiv=0; //累计概率
        
        //随机值
		$got_gift = false;
		foreach ($cc as $key => $value) {
            $ljgaiv+=$value['gailv'];
            if($cur_gailv<=$ljgaiv){
                $got_gift = $value; //中奖了,把奖品数据复制给 $got_gift
                break;
            }
        }
		if(!$got_gift) {
            //没中奖,这里复位中奖数据给$got_gift
            $got_gift = $this->noGift($cur_gailv);
        }
        $got_gift['random_val']=$cur_gailv;
        return $got_gift;
    }
    private function noGift($cur_gailv=-1,$need_gailv=0){
        $got_gift=array();
        $got_gift['id'] = 0;
        $got_gift['name'] = '未中奖';
        $got_gift['need_contact_info'] = 0;
        $got_gift['gailv'] = $need_gailv;
        $got_gift['random_val']=$cur_gailv;
        return $got_gift;

    }
}